package com.hsteach.service.equipment;

import com.google.common.collect.Lists;
import com.hsteach.common.config.App;
import com.hsteach.common.config.AppConfig;
import com.hsteach.common.exception.ServiceException;
import com.hsteach.common.utils.SecurityUtils;
import com.hsteach.common.utils.StringUtils;
import com.hsteach.dao.domain.equipment.EquipmentRepairConfig;
import com.hsteach.dao.mapper.equipment.EquipmentRepairConfigMapper;
import com.hsteach.dao.mapper.equipment.EquipmentRepairMapper;
import com.hsteach.enums.BooleanEnum;
import com.hsteach.framework.feign.client.xgk.dto.GetPersonByConditionEntity;
import com.hsteach.framework.feign.client.xgk.dto.GetPersonBySpyCodeEntity;
import com.hsteach.framework.feign.client.xgk.dto.ret.GetPersonByConditionRet;
import com.hsteach.framework.feign.client.xgk.dto.ret.GetPersonBySpyCodeRet;
import com.hsteach.framework.feign.client.xgk.dto.ret.GetTeacherRet;
import com.hsteach.framework.web.service.UApiService;
import com.hsteach.service.third.XgkService;
import com.hsteach.web.controller.equipment.dto.AddEquipmentConfigDto;
import com.hsteach.web.controller.equipment.dto.EquipmentPublicDto;
import com.hsteach.web.controller.equipment.dto.PersonVo;
import com.hsteach.web.controller.equipment.dto.UpdateEquipmentConfigDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EquipmentRepairConfigService {

    @Autowired
    private EquipmentRepairConfigMapper equipmentRepairConfigMapper;

    @Autowired
    private UApiService uApiService;

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private XgkService xgkService;

    @Autowired
    private EquipmentRepairMapper equipmentRepairMapper;

    /**
     * 根据启用状态查询维修配置列表
     * @param status
     * @return
     */
    public List<UpdateEquipmentConfigDto> queryListByStatus(int status) {
        EquipmentPublicDto dto = new EquipmentPublicDto();
        dto.setStatus(status);
        dto.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
        List<EquipmentRepairConfig> equipmentRepairConfigs = equipmentRepairConfigMapper.queryListByStatus(dto);
        Map<String, List<EquipmentRepairConfig>> group = equipmentRepairConfigs.stream().collect(Collectors.groupingBy(EquipmentRepairConfig::getRepairType));
        List<UpdateEquipmentConfigDto> datas = group.entrySet().stream().map(e -> {
            UpdateEquipmentConfigDto ret = new UpdateEquipmentConfigDto();
            EquipmentRepairConfig config = e.getValue().get(0);
            BeanUtils.copyProperties(config, ret);
            List<PersonVo> list = e.getValue().stream().map(j -> {
                PersonVo vo = new PersonVo();
                vo.setPersonId(j.getPersonId());
                vo.setPersonName(j.getPersonName());
                vo.setPersonMobile(j.getPersonMobile());
                vo.setTPersonId(j.getTPersonId());
                return vo;
            }).filter(j -> StringUtils.isNotEmpty(j.getPersonId())).collect(Collectors.toList());
            ret.setPersons(list);
            return ret;
        }).collect(Collectors.toList());
        datas = datas.stream().sorted(Comparator.comparing(UpdateEquipmentConfigDto::getId).reversed()).collect(Collectors.toList());
        return datas;
    }

    public int add(EquipmentRepairConfig equipmentRepairConfig) {
        equipmentRepairConfig.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
        return equipmentRepairConfigMapper.insert(equipmentRepairConfig);
    }

    public int addList(AddEquipmentConfigDto dto) {
        String orgCode = SecurityUtils.getAuthInfo().getOrgCode();
        EquipmentPublicDto query = new EquipmentPublicDto();
        query.setDelStatus(1);
        query.setOrgCode(orgCode);
        query.setRepairType(dto.getRepairType());
        List<EquipmentRepairConfig> equipmentRepairConfigs = equipmentRepairConfigMapper.queryListByStatus(query);
        if (equipmentRepairConfigs.size() > 0) {
            throw new ServiceException("类别已存在");
        }
        List<EquipmentRepairConfig> list = dto.getPersons().stream().map(e -> {
            EquipmentRepairConfig config = new EquipmentRepairConfig();
            BeanUtils.copyProperties(dto, config);
            config.setTPersonId(e.getTPersonId());
            config.setPersonId(e.getPersonId());
            config.setPersonName(e.getPersonName());
            config.setOrgCode(orgCode);
            return config;
        }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(list)) {
            return equipmentRepairConfigMapper.batchInsert(list);
        }
        return 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public int edit(UpdateEquipmentConfigDto dto) {
        List<EquipmentRepairConfig> configList = equipmentRepairConfigMapper.queryListByType(new EquipmentPublicDto().setRepairType(dto.getRepairType()));
        equipmentRepairConfigMapper.deleteByType(dto.getRepairType(), SecurityUtils.getAuthInfo().getOrgCode());
        AddEquipmentConfigDto add = new AddEquipmentConfigDto();
        BeanUtils.copyProperties(dto, add);
        addList(add);
        if (configList.size() > 1 && dto.getPersons().size() > 1){
            return 1;
        }
        List<Long> repairIdList = equipmentRepairMapper.queryIdsByType(new EquipmentPublicDto()
                .setRepairType(dto.getRepairType())
                .setIsDesignation(configList.size() > 1 ? BooleanEnum.TRUE.getCode() : null));
        if (!CollectionUtils.isEmpty(repairIdList)) {
            equipmentRepairMapper.batchUpdateByIds(repairIdList, dto.getPersons().size() == 1 ? dto.getPersons().get(0).getPersonId() : null);
        }
        return 1;
    }

    public List<PersonVo> getPersonByType(String type) {
        EquipmentPublicDto dto = new EquipmentPublicDto();
        dto.setStatus(1);
        dto.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
        dto.setRepairType(type);
        List<EquipmentRepairConfig> equipmentRepairConfigs = equipmentRepairConfigMapper.queryListByStatus(dto);
        List<PersonVo> ret = equipmentRepairConfigs.stream().map(e -> {
            PersonVo vo = new PersonVo();
            vo.setPersonId(e.getPersonId());
            vo.setPersonName(e.getPersonName());
            return vo;
        }).filter(e -> StringUtils.isNotEmpty(e.getPersonId())).collect(Collectors.toList());
        return ret;
    }

    public List<PersonVo> getAllRepairPerson(String searchName) {
        Long organizeId = SecurityUtils.getAuthInfo().getOrganizeId();
        //TODO 修理工角色ID 远程可能会发生变动，使用枚举+角色查询接口查询远程修理工角色ID
        String roleId = "571279888811864064";
        if (organizeId != null) {
            GetPersonByConditionEntity entity = new GetPersonByConditionEntity();
            entity.setRoleId("0");
            entity.setOrganizeId(String.valueOf(organizeId));
            //固定角色ID
            entity.setRoleId(roleId);
            //查询人员数据
            List<GetPersonByConditionRet> personByCondition = uApiService.getPersonByCondition(entity);
            //从所有人员中进行数据转化
            List<PersonVo> personVos = personByCondition.stream().map(e -> {
                PersonVo vo = new PersonVo();
                vo.setTPersonId(e.getUserId());
                vo.setPersonId(e.getUserId());
                vo.setPersonMobile(e.getMobile());
                vo.setPersonName(StringUtils.isNotEmpty(e.getUserName()) ? e.getUserName() : "未知");
                return vo;
            }).collect(Collectors.toList());
            //获取基础平台PersonId
            List<GetTeacherRet> platformData = xgkService.getTeachers(SecurityUtils.getAuthInfo().getPersonId());
            //获取ID映射Map
            Map<String, String> idMap = platformData.stream().filter(Objects::nonNull)
                    .collect(Collectors.toMap(GetTeacherRet::getT_userID, GetTeacherRet::getPersonId));
            //数据变更
            personVos.forEach(item->{
                String userId = item.getPersonId();
                item.setPersonId(idMap.get(userId));
            });
            //关键词筛选
            if (StringUtils.isNotEmpty(searchName)) {
                personVos = personVos.stream().filter(e -> e.getPersonName().contains(searchName)).collect(Collectors.toList());
            }
            return personVos;
        }
        return Lists.newArrayList();
    }
}
